from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .utils import QQOauth
from .models import OAuthQQUser
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import GenericAPIView
from .serializers import QQTokenSerializer

# Create your views here.

class QQAuthURLView(APIView):
    """
    生成url
    实现出现QQ授权登录视图
    GET /oauth/qq/statues/
    """

    def get(self, request):

        # 生成auth_url
        # https://graph.qq.com/oauth2.0/authorize
        # 请求参数请包含如下内容：
        # response_type   必须      授权类型，此值固定为“code”。
        # client_id       必须      申请QQ登录成功后，分配给应用的appid。
        # redirect_uri    必须      成功授权后的回调地址，必须是注册appid时填写的主域名下的地址，建议设置为网站首页或网站的用户中心。注意需要将url进行URLEncode。
        # state           必须      client端的状态值。用于第三方应用防止CSRF攻击，成功授权后回调时会原样带回。请务必严格按照流程检查用户与state参数状态的绑定。
        # scope              可选      scope=get_user_info

        state = request.GET['state']

        qq = QQOauth()

        auth_url = qq.get_auth_url(state)

        return Response({'auth_url':auth_url})

class QQAuthAccessTokenView(GenericAPIView):

    """
    GET  /oauth/qq/users/?code=xxx
    POST /oauth/qq/users/
    """

    def get(self,request):


        # 根据 code 换取token
        code = request.GET['code']
        if code is None:
            return Response({'message':'参数错误'},status=400)

        qq = QQOauth()

        try:
            token = qq.get_token(code)
            openid = qq.get_openid(token)
        except Exception as e:
            return Response({'message':'授权失败'},status=400)

        # 获取 openid之后，进行判断，
        try:
            #如果之前绑定过
            qquser = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:

            # 如果没有绑定过 生成注册的token

            token = OAuthQQUser.generate_save_user_token(openid)

            return Response({'access_token':token})

        else:
            user = qquser.user
            # 生成登录的token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })

    serializer_class = QQTokenSerializer

    def post(self, request):

        # 创建序列化器
        serializer = self.get_serializer(data=request.data)
        # 验证
        serializer.is_valid(raise_exception=True)
        # 数据入库
        user = serializer.save()

        # 生成登录token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })

        return response




